from flask import Flask, jsonify
from ServerService.service_checker import check_service
from ServerService.ssh_executor import ssh_exec
from ServerService.file_distributor import sftp_upload
from System.monitor_system import save_to_mysql
from flask import render_template
import pymysql

app = Flask(__name__)

#服务状态
@app.route('/serviceChecker', methods=['POST'])
def deploy_service():
    serviceName = request.form.get('serviceName')
    service_state = check_service(serviceName)
    return service_state

#批量执行命令
@app.route('/sshExecutor', methods=['POST'])
def ssh_executor():
    hosts_str = request.form.get('hosts')
    user = request.form.get('user')
    command = request.form.get('command')
    key_path = '~/.ssh/id_rsa'

    if not all([hosts_str, user, command]):
        return jsonify({"status": "error", "message": "Missing parameters"}), 400

    hosts = hosts_str.split(',')
    results = []

    for host in hosts:
        host = host.strip()
        result = ssh_exec(host, user, key_path, command)
        results.append(result)

    # 检查是否有失败
    errors = [res for res in results if res["status"] == "error"]
    if errors:
        return jsonify({"status": "partial_error", "results": results}), 207
    else:
        return jsonify({"status": "success", "results": results}), 200

@app.route('/sshUpload', methods=['POST'])
def sftp_upload():
    hosts_str = request.form.get('hosts')
    user = request.form.get('user')
    key_path = '~/.ssh/id_rsa'
    start_file = request.form.get('startFile')
    target_file = request.form.get('targetFile')

    if not all([hosts_str, user, start_file, target_file]):
        return jsonify({"status": "error", "message": "Missing parameters"}), 400

    hosts = hosts_str.split(',')
    results = []

    for host in hosts:
        host = host.strip()
        result = sftp_upload(host, user, key_path, start_file, target_file)
        results.append(result)

    # 检查是否有失败
    errors = [res for res in results if res["status"] == "error"]
    if errors:
        return jsonify({"status": "partial_error", "results": results}), 207
    else:
        return jsonify({"status": "success", "results": results}), 200

@app.route('/monitorSystem', methods=['POST'])
def save_monitor_mysql():
    try:
        save_to_mysql() 
        return jsonify({
            "status": "success",
            "message": "监控数据已成功保存到数据库"
        }), 200
    except Exception as e:
        # 记录错误日志（可选）
        app.logger.error(f"保存监控数据失败: {str(e)}")
        return jsonify({
            "status": "error",
            "message": f"保存监控数据失败: {str(e)}"
        }), 500

@app.route('/dashboard', methods=['GET']) 
def dashboard():
    db = None
    cursor = None
    try:
        # 连接数据库
        db = pymysql.connect(
            host="192.168.0.104",
            user="root",
            passwd="123123",
            db="python_monitor"
        )
        cursor = db.cursor()
        
        # 查询最近 10 条记录
        cursor.execute("SELECT * FROM metrics ORDER BY time DESC LIMIT 10")
        data = cursor.fetchall()
        
        return render_template('dashboard.html', metrics=data)
    
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": f"数据库查询失败: {str(e)}"
        }), 500
    
    finally:
        # 确保关闭资源
        if cursor:
            cursor.close()
        if db:
            db.close()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

# from flask import render_template
# import MySQLdb
#
# @app.route('/dashboard')
# def dashboard():
#     db = MySQLdb.connect(host="localhost", user="root", passwd="123123", db="python_monitor")
#     cursor = db.cursor()
#     cursor.execute("SELECT * FROM metrics ORDER BY time DESC LIMIT 10")
#     data = cursor.fetchall()
#     return render_template('dashboard.html', metrics=data)
#
# # 告警逻辑（示例：CPU超过90%触发）
# def check_alerts():
#     db = MySQLdb.connect(...)
#     cursor = db.cursor()
#     cursor.execute("SELECT cpu FROM metrics ORDER BY time DESC LIMIT 1")
#     cpu = float(cursor.fetchone()[0])
#     if cpu > 90:
#         send_email_alert("CPU usage over 90%!")
#
# def send_email_alert(message):
#     # 实现邮件发送逻辑（如smtplib）
#     pass